package com.ziyun.pop.web.modules.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.goods.constant.GoodsResult;
import com.service.model.quote.constant.AttributeValueType;
import com.service.model.quote.constant.OemCategoryType;
import com.service.quote.module.product.model.QuoteProductInfo;
import com.service.quote.module.quote.model.QuoteDto;
import com.service.quote.module.quote.model.QuoteResult;
import com.utility.StringUtils;
import com.utility.http.HttpUtils;
import com.ziyun.pop.common.e.DeleteEnum;
import com.ziyun.pop.common.e.logistics.LogisticsLogiTypeEnum;
import com.ziyun.pop.common.e.logistics.LogisticsSendTypeEnum;
import com.ziyun.pop.common.e.order.*;
import com.ziyun.pop.common.utils.JsonUtils;
import com.ziyun.pop.common.utils.MapCloneUtils;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.erpOrderLog.entity.ErpOrderLogEntity;
import com.ziyun.pop.modules.logistics.dto.ErpLogisticsDto;
import com.ziyun.pop.modules.logistics.service.LogisticsTypeService;
import com.ziyun.pop.modules.order.dto.*;
import com.ziyun.pop.modules.order.entity.*;
import com.ziyun.pop.modules.order.service.ErpOrderAllotRelevanceService;
import com.ziyun.pop.modules.order.service.ErpOrderService;
import com.ziyun.pop.modules.order.service.OrderTaxService;
import com.ziyun.pop.modules.orderRemarks.service.OrderRemarksService;
import com.ziyun.pop.modules.production.dto.TwbOrderSuppPaymentDto;
import com.ziyun.pop.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.pop.modules.production.service.ErpOrderItemService;
import com.ziyun.pop.modules.production.service.ErpOrderProductionService;
import com.ziyun.pop.modules.production.vo.ErpOrderProductionListVo;
import com.ziyun.pop.modules.quoteParts.entity.QuotePartsEntity;
import com.ziyun.pop.modules.storeFavouredPrice.service.StoreFavouredPriceService;
import com.ziyun.pop.modules.storeGoodsCategory.entity.StoreGoodsCategoryEntity;
import com.ziyun.pop.modules.storeGoodsCategory.service.StoreGoodsCategoryService;
import com.ziyun.pop.modules.storeGoodsProduct.entity.StoreGoodsProductEntity;
import com.ziyun.pop.modules.storeGoodsProduct.service.StoreGoodsProductService;
import com.ziyun.pop.modules.storeMember.entity.UserBaseInfoEntity;
import com.ziyun.pop.modules.storeMember.service.UserBaseInfoService;
import com.ziyun.pop.modules.supp.entity.SellerInfoEntity;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import com.ziyun.pop.modules.userWallet.entity.UserWalletEntity;
import com.ziyun.pop.modules.userWallet.service.UserWalletService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import net.sf.json.JSONArray;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.service.goods.api.GoodsService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


/**
 * erp订单信息表
 *
 * @author llc
 * @date 2018-09-27 11:19:18
 */
@RequestMapping("order/erporder")
@RestController
public class ErpOrderController {
    private  static Logger logger = LoggerFactory.getLogger(ErpOrderController.class);

    @Value("${erpApi}")
    private String erpApi ;

    @Autowired
    private ErpOrderService erpOrderService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ErpOrderItemService erpOrderItemService;

    @Autowired
    private StoreGoodsCategoryService storeGoodsCategoryService;

    @Autowired
    private StoreGoodsProductService storeGoodsProductService;

    @Autowired
    private OrderRemarksService orderRemarksService;

    @Autowired
    private SellerInfoService sellerInfoService;

    @Autowired
    private LogisticsTypeService logisticsTypeService;

    @Autowired
    private UserBaseInfoService userBaseInfoService;

    @Autowired
    private StoreFavouredPriceService storeFavouredPriceService;

    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private ErpOrderProductionService erpOrderProductionService;

    @Autowired
    private  GoodsService goodsService;

    @Autowired
    private OrderTaxService orderTaxService;

    @Autowired
    private ErpOrderAllotRelevanceService erpOrderAllotRelevanceService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    /*@RequiresPermissions("order:erporder:list")*/
    public R list(@RequestParam Map<String, Object> params){
        params.put("sellerId",UserUtils.getCurentUser().getSellerId());
        //查询当前门店的业务员
        List<String> salesManList= erpOrderService.querySalesManList(UserUtils.getCurentUser().getSellerId());
        //先获取当前的sell_id
        // 查询省市区级联数据
        List<String> area =erpOrderService.queryRegionsSascade();
        //查询所有门店商品分类
        List<StoreGoodsCategoryEntity>  categoryData=storeGoodsCategoryService.getStoreGoodsCategoryList();
        Map<String,Object> userData = new HashMap<>();
        userData.put("categoryData",categoryData);
        userData.put("area",JSONArray.fromObject(area).toString());
        userData.put("salesManList",salesManList);
        userData.put("orderSourceEnum",JsonUtils.enumToList(OrderSourceEnum.class));
        PageUtils page =erpOrderService.queryPageErpOrderList(params);
        return R.ok().put("page", page).put("userData",userData);
    }

    /**
     * 客户列表
     */
    @RequestMapping("/queryUser")
    /*@RequiresPermissions("order:erporder:list")*/
    public R userList(@RequestParam Map<String, Object> params){
        //从user_base_info（用户信息表）表查询客户信息
        params.put("sellerId",UserUtils.getCurentUser().getSellerId());
        List<UserBaseInfoEntity>  userInfoData= userBaseInfoService.queryUserList(params);
        return R.ok().put("userInfoData",userInfoData);
    }

    /**
     * 根据选择的客户查业务员
     */
    @RequestMapping("/getMerchantsSalesMan/{merchantsSalesMan}")
    public R getMerchantsSalesMan(@PathVariable String merchantsSalesMan){
        if(StringUtils.isNotBlank(merchantsSalesMan)){
            List<SysUserEntity> sysUserEntities = sysUserService.list(new QueryWrapper<SysUserEntity>().eq("user_id", merchantsSalesMan).eq("status",1));
            List<String> salesManList=sysUserEntities.stream().map(SysUserEntity::getUsername).collect(Collectors.toList());
            return R.ok().put("salesManList",salesManList);
        }else{
            return R.ok();
        }
    }

    /**
     *  初始化查询10条
     * @param
     * @return
     */
    @RequestMapping("/queryPageUser")
    public R queryPageUser(){
        Long sellerId=UserUtils.getCurentUser().getSellerId();
        List<UserBaseInfoEntity> userInfoData =userBaseInfoService.queryPageUser(sellerId);
        return R.ok().put("userInfoData",userInfoData);
    }

    /**
     *  查询接单员列表以及快印，商务印刷的分类（二级）
     * @param
     * @return
     */
    @RequestMapping("/addData")
    public R queryAddData(){
        //先获取当前的sell_id
        Long sellerId=UserUtils.getCurentUser().getSellerId();
        List<SysUserEntity> acceptOrderUserData =sysUserService.getAcceptOrderUserlist(sellerId);
        //商务印刷商品分类
        List<StoreGoodsCategoryEntity> shangWuCategoryData=storeGoodsCategoryService.getPrintCategoryList();
        //快印商品分类
        List<StoreGoodsCategoryEntity> fastCategoryData=storeGoodsCategoryService.getFastCateoryList();
        //返回当前门店下所有人员姓名以及当前登陆人姓名

        // 查询省市区级联数据
        List<String> area =erpOrderService.queryRegionsSascade();
        return R.ok().put("acceptOrderUserData",acceptOrderUserData).put("currentUser",UserUtils.getCurentUser().getUsername())
                .put("shangWuCategoryData",shangWuCategoryData)
                .put("area",JSONArray.fromObject(area).toString())
                .put("fastCategoryData",fastCategoryData);
    }

    /**
     *  根据所选的商品的商品在goods_category表中的id查询报价信息
     * @param
     * @return
     */
    @RequestMapping("/getQuoteGoods/{categoryId}")
    public R  getQuoteGoods(@PathVariable("categoryId") Integer categoryId){
        Map<String,Object> quoteProductInfo=getQuote(categoryId);
        if(quoteProductInfo.size()==0){
            return R.error("获取报价参数错误");
        }
        return R.ok().put("quoteProductInfo",quoteProductInfo);
    }

    /**
     * 调用接口获取报价信息
     */
    private Map<String,Object> getQuote(Integer categoryId){
        Map<String,Object> quoteProductInfo=new HashMap<>();

        GoodsResult<QuoteProductInfo> res=goodsService.getQuoteGoods(categoryId);
        String str=JsonUtils.object2String(res);
        logger.info("获取报价商品产品接口返回参数"+categoryId+"----------"+str);
        if (res.getCode() != 1){
            logger.error("报价下单，返回结果失败，分类id："+categoryId);
        } else {
            List<QuotePartsEntity> quotePartsList =  (List<QuotePartsEntity>)com.alibaba.fastjson.JSONObject.toJSON(res.getData().getQuotePartsList());
            String categoryType = res.getData().getCategoryType().toString();
            quoteProductInfo.put("quotePartsList",quotePartsList);
            quoteProductInfo.put("categoryType",categoryType);
        }
        return quoteProductInfo;

    }
    /**
     *  根据categoryID查询当前分类下的商品及其价格
     * @param
     * @return
     */
    @RequestMapping("/productInfo/{categoryId}/{memberId}")
    public R productInfo(@PathVariable("categoryId") Integer categoryId,@PathVariable("memberId") Integer memberId){
        Map<String, Object> params=new HashMap<String, Object>();
        //封装参数
        params.put("disabled",0);
        params.put("del",0);
        params.put("categoryId",categoryId);
        if(memberId==898855){
            params.put("sellerId",20);
        }else{
            params.put("sellerId",UserUtils.getCurentUser().getSellerId());
        }
        List<StoreGoodsProductEntity> goodsData=storeGoodsProductService.productSearch(params);
        return R.ok().put("goodsData",goodsData);
    }


    /**
     *  根据productName进行查询
     * @param
     * @return
     */
    @PostMapping("/productSearch")
    public R productSearch(@RequestParam Map<String, Object> params){
        //封装参数
        params.put("disabled",0);
        params.put("del",0);
        if(params.get("memberId").toString().equals("898855")){
            params.put("sellerId",20);
        }else{
            params.put("sellerId",UserUtils.getCurentUser().getSellerId());
        }
        //查询出商品及其阶梯价格
        List<StoreGoodsProductEntity> goodsData=storeGoodsProductService.productSearch(params);
        return R.ok().put("goodsData",goodsData);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{orderNo}")
    // @RequiresPermissions("order:erporder:info")
    public R info(@PathVariable("orderNo") String orderNo){
        return  erpOrderService.getErpOrderInfo(orderNo);
    }

    //修改订单加急状态
    @RequestMapping("/orderUrgent/{orderNo}")
    /* @RequiresPermissions("order:erporder:info")*/
    public R orderUrgent(@PathVariable("orderNo") String orderNo) {
        return erpOrderService.orderUrgent(orderNo);
    }

    //生产完成
    @RequestMapping("/finishOrderItem/{orderNo}")
    public R finishOrderItem(@PathVariable("orderNo") String orderNo) {
        return  erpOrderService.finishOrderItem(orderNo);
    }

    //新增备注
    @RequestMapping("/addRemark")
    public R addRemark(@RequestBody  OrderRemarksEntity orderRemarks){
        //先根据订单号判断订单的生产状态
        ErpOrderEntity erpOrderEntity =erpOrderService.getById(orderRemarks.getOrOrderId());
        if(erpOrderEntity.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
            return R.error("已完成订单无法新增备注");
        }
        if(orderRemarks!=null){
            orderRemarks.setOrCreateName(UserUtils.getCurentUser().getUsername());
            orderRemarksService.save(orderRemarks);
        }
        return R.ok();
    }
    /**
     * 订单撤回
     * 生产完成-》生产中-》新开单
     */
    @RequestMapping("/orderRecall/{orderNo}")
    public R orderRecall(@PathVariable("orderNo") String orderNo){
        return  erpOrderService.orderRecall(orderNo);
    }

    //取消订单
    @RequestMapping("/cancelOrder")
    public R cancelOrder (@RequestBody ErpOrderLogEntity erpOrderLogs){
        erpOrderLogs.setCreateName(UserUtils.getCurentUser().getUsername());
        //取消订单
        return erpOrderService.cancelOrder(erpOrderLogs);
    }

    //修改支付方式
    @RequestMapping("/updatePayType")
    @RequiresPermissions("order:erporder:payType")
    public  R updatePayType(@RequestBody ErpOrderEntity erpOrder){
        return  erpOrderService.updatePayType(erpOrder);
    }

    //查询订单出库所需参数
    @RequestMapping("/searchLogisticData/{orderNo}")
    public R searchLogisticData(@PathVariable String orderNo){
        //查询订单信息
        if(!StringUtils.isNotBlank(orderNo)){
            return  R.error("异常错误，请联系管理员!");
        }
        //查询订单信息
        ErpOrderEntity erpOrder=erpOrderService.getById(orderNo);
        //订单如果物流成本已经录入完成，则不允许添加物流
        if(erpOrder.getCommissionStatus()!=CommissionStatusEnum.NOTENTERED.toInt()){
            return R.error("物流成本已录入完成的订单不允许添加物流!");
        }
        //先查询seller_info信息
        SellerInfoEntity sellerInfo=sellerInfoService.getById(UserUtils.getCurentUser().getSellerId());

        //查询商品详情
        List<ErpOrderItemEntity> erpOrderItemData=erpOrderItemService.list(new QueryWrapper<ErpOrderItemEntity>().eq("order_no",orderNo));
        // 查询省市区级联数据
        List<String> area =erpOrderService.queryRegionsSascade();
        List<Map<Integer,String>> logisticsTypeList= logisticsTypeService.queryTypeList();
        return R.ok().put("logisticsLogiTypeEnum",JsonUtils.enumToList(LogisticsLogiTypeEnum.class))
                .put("LogisticsSendTypeEnum",JsonUtils.enumToList(LogisticsSendTypeEnum.class))
                .put("sellerInfo",sellerInfo).put("erpOrder",erpOrder)
                .put("erpOrderItemData",erpOrderItemData)
                .put("logisticsTypeList",logisticsTypeList)
                .put("area",JSONArray.fromObject(area).toString());
    }

    //订单出库前先查询订单的来源以及挂账
    @RequestMapping("/getHangingOrderOutMsg/{orderNo}")
    public R getHangingOrderOutMsg(@PathVariable String orderNo ){
        boolean flag=false;
        //先查询当前订单是否为挂账订单或紫云网订单
        ErpOrderEntity erpOrder = erpOrderService.getById(orderNo);
        if(erpOrder.getOrderSource()==1||erpOrder.getOnCredit()==true){
            flag=true;
        }
        return  R.ok().put("flag",flag);
    }



    //订单出库
    @RequestMapping("/saveErpOrderLogistics")
    public R saveErpOrderLogistics(@RequestBody ErpLogisticsDto erpLogisticsDto){
        return erpOrderService.saveErpOrderLogistics(erpLogisticsDto);
    }

    /**
     * singleOrderItemDetail
     */
    @RequestMapping("/singleOrderItemDetail/{eoItemId}")
    public R singleOrderItemDetail(@PathVariable  Integer eoItemId){
        ErpOrderItemEntity singleOrderItemDetail=  erpOrderItemService.getById(eoItemId);
        return R.ok().put("singleOrderItemDetail",singleOrderItemDetail);
    }

    /**
     * 订单商品分配
     * @param orderItemAllotDto
     * @return
     */
    @RequestMapping("/allotOrderItem")
    public R allotOrderItem(@RequestBody OrderItemAllotDto orderItemAllotDto){
        Long userId = UserUtils.getCurentUser().getUserId();
        orderItemAllotDto.setUserId(userId.intValue());
        return erpOrderService.allotOrderItem(orderItemAllotDto);
    }

    /**
     *添加订单
     */
    @RequestMapping("/save")
    @ResponseBody
    /* @RequiresPermissions("order:erporder:save")*/
    public R save(@RequestBody ErpOrderItemDto ErpOrderItemDto){
        return    erpOrderService.saveErpOrderWithItem(ErpOrderItemDto);
    }

    //收银前查询的相关数据
    @RequestMapping("/getReceviceMoneyData/{orderNo}")
    @RequiresPermissions("order:erporder:money")
    public R getReceviceMoneyData(@PathVariable String orderNo ){
        //查询订单总额等相关信息
        ErpOrderEntity erpOrder=erpOrderService.getById(orderNo);
        //判断订单状态，如果为已完结，则直接提示
        if(erpOrder.getProductionStatus()==ProductionStatusEnum.FINISH.toInt()){
            return  R.error("已完成订单无法进行收银操作!请刷新页面查看订单最新状态!");
        }
        if(erpOrder.getProductionStatus()!=4){
            return  R.error("只有生产完成的订单才能进行收银操作!");
        }
        //根据会员查询会员折扣
        Integer memberId = erpOrder.getMemberId();
        //当前用户sellerID
        Long sellerId=UserUtils.getCurentUser().getSellerId();
        //根据会员名查询折扣率
        Map<String,Object> map=new HashMap<>();
        map.put("memberId",memberId);
        map.put("sellerId",sellerId);
        BigDecimal discountRate=storeFavouredPriceService.getDiscountRateByMemberId(map);
        //定义一个变量存储用户余额
        BigDecimal advance=new BigDecimal(0);
        //查询用户余额度
        UserWalletEntity userWallet= userWalletService.getById(memberId);
        if(userWallet!=null){
            advance=userWallet.getAdvance();
        }
        // 优惠金额 
        BigDecimal pmtGoods = erpOrder.getPmtGoods() == null ? BigDecimal.ZERO : erpOrder.getPmtGoods();
        BigDecimal pmtOrder = erpOrder.getPmtOrder() == null ? BigDecimal.ZERO : erpOrder.getPmtOrder();
        BigDecimal pmtRandom = erpOrder.getPmtRandom() == null ? BigDecimal.ZERO : erpOrder.getPmtRandom();
        BigDecimal totalDiscount = pmtGoods.add(pmtOrder).add(pmtRandom);

        // 应付金额
        BigDecimal payableAmount = erpOrder.getPayableAmount();
        BigDecimal payed = erpOrder.getPayed() == null ? BigDecimal.ZERO : erpOrder.getPayed();
        BigDecimal money = payableAmount.subtract(payed);

        // 将数据重新封装传给前台
        Map<String,Object> recMoney=new HashMap<>();
        recMoney.put("discountRate",discountRate==null?0:discountRate);
        recMoney.put("orderNo",erpOrder.getOrderNo());
        recMoney.put("memberName",erpOrder.getMemberName());
        recMoney.put("totalMount",erpOrder.getTotalAmount());
        recMoney.put("discount",erpOrder.getDiscount());
        recMoney.put("payableAmount",money);
        recMoney.put("money",money);
        recMoney.put("payed",payed);
        recMoney.put("advance",advance);
        recMoney.put("memberId",memberId);
        recMoney.put("totalDiscount",totalDiscount);
        recMoney.put("payName","扫码支付");//默认扫码支付
        return R.ok().put("payTypeEnum",JsonUtils.enumToList(PayTypeEnum.class))
                .put("recMoney",recMoney);
    }

    @PostMapping("/getBatchReceviceMoneyData")
    @RequiresPermissions("order:erporder:money")
    //批量收银结算
    public R getBatchReceviceMoneyData(@RequestBody List<String> orderNoList ){
        return erpOrderService.getBatchReceviceMoneyData(orderNoList);
    }


    //收银结算
    @RequestMapping("/saveReceviceMoney")
    public R saveReceviceMoneyData(@RequestBody Map<String,Object> params ) {
        return erpOrderService.saveReceviceMoneyData(params);
    }

    //批量收银结算
    @RequestMapping("/saveBatchReceviceMoney")
    public R saveBatchReceviceMoney(@RequestBody Map<String,Object> params ) {
        return erpOrderService.saveBatchReceviceMoney(params);
    }


    //开始扫码支付
    @RequestMapping("/sweepCodeBegin")
    public R sweepCodeBegin(@RequestBody Map<String,Object> params ) {
        return erpOrderService.sweepCodeBegin(params);
    }

    //批量开始扫码支付
    @RequestMapping("/batchSweepCodeBegin")
    public R batchSweepCodeBegin(@RequestBody Map<String,Object> params ) {
        return erpOrderService.batchSweepCodeBegin(params);
    }


    //扫码支付 回调
    @RequestMapping("/sweepCodeCallBack")
    public R sweepCodeCallBack(@RequestBody Map<String,Object> params ) {
        return erpOrderService.sweepCodeCallBack(params);
    }

    //扫码支付 回调
    @RequestMapping("/batchSweepCodeCallBack")
    public R batchSweepCodeCallBack(@RequestBody Map<String,Object> params ) {
        return erpOrderService.batchSweepCodeCallBack(params);
    }

    /**
     * 紫云网订单撤回
     */
    @RequestMapping("/ziyunOrderBack/{orderNo}")
    public R ziyunOrderBack(@PathVariable String orderNo){
        return erpOrderService.ziyunOrderBack(orderNo);
    }

    /**
     * 修改订单
     */
    @RequestMapping("/update")
    /*  @RequiresPermissions("order:erporder:update")*/
    public R update(@RequestBody ErpOrderItemDto erpOrderItemDto){
        return erpOrderService.updateByOrderNo(erpOrderItemDto);
    }

    /**
     * 批量录入
     * @param ids
     * @return
     */
    @RequestMapping("/batchEnter")
    public R batchEnter(@RequestParam("ids") String ids ){
        String createName=UserUtils.getCurentUser().getUsername();
        String createBy=UserUtils.getCurentUser().getUserId().toString();
        return   erpOrderService.batchEnter(ids,createName,createBy);
    }

    /**
     * 修改收货人信息
     */
    @RequestMapping("/orderReceiverUpdate")
    @ResponseBody
    @RequiresPermissions("order:erporder:update")
    public R orderReceiverUpdate(@RequestBody ErpOrderEntity erpOrder){
        ValidatorUtils.validateEntity(erpOrder);
        String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
        //用户ID
        Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
        Map<String, Object> paramBodyMap = new HashMap<String, Object>();
        paramBodyMap.put("erpOrder",JsonUtils.object2String(erpOrder));
        paramBodyMap.put("username",username);
        paramBodyMap.put("userId",userId);
        String url = erpApi + "/order/erporder/orderReceiverUpdate";
        String response =  HttpUtils.doPost(url,paramBodyMap);
        R rs = JsonUtils.string2Object(response, R.class);
        return rs;
    }

    /**
     * 打印修改订单状态
     */
    @GetMapping("/updateStatus/{orderNo}/{status}")
    public R updateStatus(@PathVariable("orderNo") String orderNo,@PathVariable("status") Integer status) {
        return erpOrderService.updateStatus(orderNo,status);
    }

    /**
     * 获取打印结算单所需数据
     */
    @GetMapping("/printBalance/{orderNo}")
    public R printBalance(@PathVariable("orderNo") String orderNo) {
        SysUserEntity curentUser = UserUtils.getCurentUser();
        SellerInfoEntity sellerInfoEntity = sellerInfoService.getById(curentUser.getSellerId());
        R re = R.ok();
        // 订单信息
        ErpOrderEntity erpOrder =  erpOrderService.getErpOrder(orderNo);
//        ErpOrderEntity erpOrder =  erpOrderService.getById(orderNo);
        re.put("erpOrder", erpOrder);
        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );
        re.put("orderItemDetailData", orderItemDetailData);
        re.put("curentUser",curentUser);
        re.put("sellerInfoEntity",sellerInfoEntity);
        return re;

    }


    /**
     * 商务印刷算价
     */
    @RequestMapping("/caculateQuote")
    public R caculateQuote(@RequestBody HashMap<String,Object> params){
        if(!StringUtils.isNotBlank(params.get("categoryType").toString())){
            return R.error("参数错误，请联系管理员");
        }
        //获取当前的sellerID
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        //判断是否为自营
        SellerInfoEntity sellerInfoEntity=sellerInfoService.getById(sellerId);
        //如果为自营.则工厂id全部为1
        if(sellerInfoEntity.getSelf()==1){
            params.put("factoryId",1);
        }else{
            params.put("factoryId",sellerId);
        }
        if(params.get("memberId")!=null){
            //如果是紫云分配这个客户，factoryId设置为20，写死
            if(params.get("memberId").toString().equals("898855")){
                params.put("factoryId",20);
            }
        }
        //移除memberid,请求接口
        params.remove("memberId");

        //定义一个map记录处理前的parmas
        HashMap<String,Object> paramsCopy= MapCloneUtils.clone(params);
        QuoteDto quoteDto=dealCaculateQuote(params);
        //调用算价服务
        String quoteStr=JsonUtils.object2String(quoteDto);
        logger.info("商务印刷商品算价请求数据:"+quoteStr);
        GoodsResult<QuoteResult> factoryQuote = goodsService.findFactoryQuote(quoteDto);
        String req=JsonUtils.object2String(factoryQuote);
        logger.info("商务印刷商品算价请求数据算价返回结果:"+req);
        //处理返回的结果
        FactoryQuoteInfo factoryQuoteInfo= dealQuoteData(req);
        if(factoryQuoteInfo==null){
            return R.error("未找到合适的算价信息!");
        }
        //数量
        Integer quantity=factoryQuoteInfo.getQuantity().intValue();
        //根据当前数量n获取n/4,n/2,n,2n,3n的价格相关信息
        List<FactoryQuoteInfo> factoryQuoteInfoList=getOtherFactoryQuoteInfo(paramsCopy,quantity);
        if(factoryQuoteInfoList.size()!=4){
            return R.error("未找到合适的报价信息!");
        }else{
            factoryQuoteInfoList.add(2,factoryQuoteInfo);
        }
        return R.ok().put("factoryQuoteInfoList",factoryQuoteInfoList);
    }

    //调用接口获取剩余四种数量的价格及相关信息
    private List<FactoryQuoteInfo> getOtherFactoryQuoteInfo(HashMap<String,Object> params,Integer quantity){
        List<FactoryQuoteInfo> factoryQuoteInfoList=new ArrayList<FactoryQuoteInfo>();
        //根据传入的数量先生成一个数量集合
        List<Integer> quantityList=new ArrayList<Integer>();
        Integer  quantity1= ((int) (Math.ceil(quantity * 1.0 / 4)));
        Integer  quantity2= ((int) (Math.ceil(quantity * 1.0 / 2)));
        Integer  quantity4= quantity * 2;
        Integer  quantity5= quantity * 3;
        quantityList.add(quantity1);
        quantityList.add(quantity2);
        quantityList.add(quantity4);
        quantityList.add(quantity5);
        //遍历将数量进行更改并调用接口，返回最终需要的结果
        for(int i=0;i<quantityList.size();i++){
            Integer quant=quantityList.get(i);
            params=addQuantity(params,quant);
            //处理params中为空的数据
            QuoteDto quoteDto = dealCaculateQuote(params);
            GoodsResult<QuoteResult> factoryQuote = goodsService.findFactoryQuote(quoteDto);

            if(factoryQuote!=null) {
                String req = JsonUtils.object2String(factoryQuote);
                FactoryQuoteInfo factoryQuoteInfo = dealQuoteData(req);
                if (factoryQuoteInfo != null) {
                    factoryQuoteInfoList.add(factoryQuoteInfo);
                }
            }
        }
        return factoryQuoteInfoList;
    }

    //封装数量到map中
    public HashMap<String,Object> addQuantity(HashMap<String,Object> params,Integer quantity){
        HashMap<String,Object> definitionValueMap= (HashMap<String, Object>) params.get("definitionValueMap");
        for (String key1:definitionValueMap.keySet()){
            HashMap<String,Object> secondMap= (HashMap<String,Object>)definitionValueMap.get(key1);
            if(secondMap.containsKey("quantity")){
                HashMap<String,Object> thirdMap= (HashMap<String, Object>) secondMap.get("quantity");
                thirdMap.put("0",quantity);
                break;
            }
        }
        return params;
    }

    //处理提交给接口的数据
    private QuoteDto dealCaculateQuote(Map<String,Object> params){
        Integer categoryId=Integer.parseInt(params.get("categoryId").toString());
        //定义一个Map用于存放最终请求接口的数据
        Map<String,Object> quoteMap=new HashMap<>();

        //处理attributeMap中为空的属性
        Map<String,Object>  attributesMap= ((Map<String, Object>) params.get("attributesMap"));
        Iterator<Map.Entry<String,Object>> attributeMapIt = attributesMap.entrySet().iterator();
        while(attributeMapIt.hasNext()){
            Map.Entry<String,Object> entry=attributeMapIt.next();
            if(((Map)entry.getValue()).size()==0){
                attributeMapIt.remove();
            }else{
                Map<String,Object> value = (Map<String, Object>) entry.getValue();
                List<String> strList=new ArrayList<>();
                for (String key :value.keySet()){
                    if(value.get(key).equals("")||null==value.get(key)){
                        strList.add(key);
                    }
                }
                for (int i = 0; i < strList.size(); i++) {
                    value.remove(strList.get(i));
                }
            }
        }
        quoteMap.put("categoryType",params.get("categoryType").toString());
        quoteMap.put("attributesMap",attributesMap);
        //处理selfPaperParts
        //先定义一个数组用于selfPaperParts的数组
        Set<Integer> selfPaperParts =new HashSet<>();
        Map<String,Boolean>    selfPaperPartsMap= ((Map<String, Boolean>) params.get("selfPaperParts"));
        for (String key :selfPaperPartsMap.keySet()){
            if(selfPaperPartsMap.get(key)){
                selfPaperParts.add(Integer.valueOf(key));
            }
        }
        //以数组形式存放数据
        quoteMap.put("selfPaperParts",selfPaperParts);

        //处理definitionValueMap
        Map<String,Map<String,Map<String,Object>>>  definitionValue= ((Map<String, Map<String,Map<String,Object>>>) params.get("definitionValueMap"));
        Iterator<Map.Entry<String,Map<String,Map<String,Object>>>> definitionValueIt = definitionValue.entrySet().iterator();
        while(definitionValueIt.hasNext()){
            Map.Entry<String,Map<String,Map<String,Object>>> entry=definitionValueIt.next();
            if(entry.getValue().size()>0){
                //如果第三层有空数据，从map中移除
                Iterator<Map.Entry<String,Map<String,Object>>>  seciter = entry.getValue().entrySet().iterator();
                while(seciter.hasNext()){
                    Map.Entry<String,Map<String,Object>> entry2 = seciter.next();
                    if(entry2.getValue().size()>0){
                        //第四层数据可能为空字符串
                        Iterator<Map.Entry<String,Object>>  thiiter = entry2.getValue().entrySet().iterator();
                        if(thiiter.hasNext()){
                            while(thiiter.hasNext()){
                                Map.Entry<String,Object> entry3 = thiiter.next();
                                if(entry3.getValue().equals("")){
                                    thiiter.remove();
                                }
                            }
                        }
                    }
                    if(entry2.getValue().size()==0){
                        seciter.remove();
                    }
                }
            }
            if(entry.getValue().size()==0){
                definitionValueIt.remove();
            }
        }
        //定义一个map用于接收definitionValueMap处理后的数据
        Map<Integer,Map<String,Object>>  definitionValueMap=new HashMap<Integer, Map<String, Object>>();
        //遍历definitionValue,将其中的value以数据形式存储
        for (String key1 :definitionValue.keySet()){
            Map<String,Map<String,Object>> firstMap=definitionValue.get(key1);
            //定义一个map封装数据
            Map<String,Object> thridMap=new HashMap<>();
            for (String key2: firstMap.keySet()){
                Map<String,Object> secondMap=firstMap.get(key2);
                List<String> strList=new ArrayList<String>();
                for (String key3:secondMap.keySet()){
                    strList.add(secondMap.get(key3).toString());
                }
                thridMap.put(key2,strList.toArray(new String[0]));
            }
            definitionValueMap.put(Integer.valueOf(key1),thridMap);
        }

        quoteMap.put("definitionValueMap",definitionValueMap);


        Map<String, Map<String, Integer>> attrMap= (Map<String, Map<String, Integer>>) quoteMap.get("attributesMap");
        String categoryType=quoteMap.get("categoryType").toString();
        //封装查询数据
        Map<Integer, Map<AttributeValueType, Integer>> attribuMap=new HashMap<Integer, Map<AttributeValueType, Integer>>();
        for (String key1:attrMap.keySet()){
            Map<String, Integer> secMap=attrMap.get(key1);
            Map<AttributeValueType,Integer> newMap=new HashMap<AttributeValueType,Integer>();
            for (String key2:secMap.keySet()){
                AttributeValueType attributeValueType = AttributeValueType.valueOf(AttributeValueType.class, key2);
                newMap.put(attributeValueType,secMap.get(key2));
            }
            attribuMap.put(Integer.valueOf(key1),newMap);
        }
        //自定义
        Map<Integer, Map<String, String[]>> defiMap= (Map<Integer, Map<String, String[]>>) quoteMap.get("definitionValueMap");
        //便利自定义map重新封装成需要的对象
        Map<Integer,Map<AttributeValueType, String[]>> definitionMap=new HashMap<Integer,Map<AttributeValueType, String[]>>();
        for (Integer key1:defiMap.keySet()){
            Map<String, String[]> stringMap = defiMap.get(key1);
            Map<AttributeValueType,String[]> newMap=new HashMap<AttributeValueType,String[]>();
            for (String key2:stringMap.keySet()){
                AttributeValueType attributeValueType = AttributeValueType.valueOf(AttributeValueType.class, key2);
                newMap.put(attributeValueType,stringMap.get(key2));
            }
            definitionMap.put(Integer.valueOf(key1),newMap);
        }

        System.out.print(definitionMap);
        Set<Integer> selfPaperPartsSet= (Set<Integer>) quoteMap.get("selfPaperParts");
        //封装对象进行请求
        QuoteDto quoteDto = new QuoteDto();
        Long factoryId=Long.valueOf(params.get("factoryId").toString());
        OemCategoryType oemCategoryTypeV = OemCategoryType.valueOf(categoryType);
        quoteDto.setFactoryId(factoryId);
        quoteDto.setCategoryType(oemCategoryTypeV);
        quoteDto.setAttributesMap(attribuMap);
        quoteDto.setDefinitionValueMap(definitionMap);
        quoteDto.setSelfPaperParts(selfPaperParts);
        quoteDto.setCategoryId(categoryId);
        return quoteDto;
    }


    //解析算价接口返回的数据
    private FactoryQuoteInfo dealQuoteData(String req){
        FactoryQuoteInfo factoryQuoteInfo=new FactoryQuoteInfo();
        Map<String,Object> resultMap=JsonUtils.jsonToMap(req);
        if(resultMap.get("code").toString().equals("1")){
            if(resultMap.get("data")!=null){
                //先获取data中的数据
                Map<String,Object> dataMap=(Map<String,Object>)resultMap.get("data");
                //productId
                Integer productId=Integer.valueOf(((Map<String,Object>)dataMap.get("productVO")).get("productId").toString());
                //处理productInfoParamList中的数据
                String productInfoParamListString=((Map<String,Object>)dataMap.get("productVO")).get("productInfoParamList").toString();
                //解析成集合
                List<ProductInfoParam> productInfoParamList= addon2ProductInfoParamList(productInfoParamListString);
                //拼接成addon;
                StringBuilder addonBuilder=new StringBuilder();
                for (int i=0;i<productInfoParamList.size();i++){
                    ProductInfoParam productInfoParam = productInfoParamList.get(i);
                    addonBuilder.append(productInfoParam.getPartsName()).append(":").append(productInfoParam.getBasicParamStr()).append(";");
                }
                //数量
                BigDecimal quantity=new BigDecimal(((Map<String,Object>)dataMap.get("productVO")).get("quantity").toString());
                //productName
                String productName=((Map<String,Object>)dataMap.get("productVO")).get("productName").toString();
                //获取工厂信息集合
                List<Map<String,Object>>  factoryQuoteInfos= JsonUtils.string2Collection( dataMap.get("factoryQuoteInfos").toString(),List.class,Map.class);

                Map<String,Object> factoryQuoteInfosMap=factoryQuoteInfos.get(0);
                //获取factoryInfoVO
                Map<String,Object> factoryInfoVoMap= (Map<String, Object>) factoryQuoteInfosMap.get("factoryInfoVO");
                Integer goodsId= (Integer) factoryInfoVoMap.get("goodsId");
                //获取attributeMap数据存放到attributeOption中
                Map<String,Object> quoteDtoMap= (Map<String, Object>) factoryQuoteInfosMap.get("quoteDto");
                String attributeOption=JsonUtils.map2String((Map<String,Object>) quoteDtoMap.get("attributesMap"));
                //definitionValueMap存放到quote_self_define_param
                String quoteSelfDefineParam=JsonUtils.map2String((Map<String,Object>) quoteDtoMap.get("definitionValueMap"));
                //得到paperInfoVOs
                List<Map<String,Object>> paperInfoVOs= (List<Map<String, Object>>) factoryQuoteInfosMap.get("paperInfoVOs");
                //将cutModel数据重新封装
                Map<String,Object> cutmodelMap=new HashMap<String, Object>();
                for(int i=0;i<paperInfoVOs.size();i++){
                    String partId= paperInfoVOs.get(i).get("partId").toString();
                    Object cutModel= paperInfoVOs.get(i).get("cutModel");
                    cutmodelMap.put(partId,cutModel);
                }
                BigDecimal totalPrice=new BigDecimal(factoryQuoteInfos.get(0).get("totalPrice").toString());
                BigDecimal unitPrice=totalPrice.divide(quantity,2,RoundingMode.HALF_UP);
                String priceProcess=factoryQuoteInfos.get(0).get("priceProcess").toString();
                factoryQuoteInfo.setProductName(productName);
                factoryQuoteInfo.setTotalPrice(totalPrice);
                factoryQuoteInfo.setPriceProcess(priceProcess);
                factoryQuoteInfo.setProductId(productId);
                factoryQuoteInfo.setQuantity(quantity);
                factoryQuoteInfo.setUnitPrice(unitPrice);
                factoryQuoteInfo.setAddon(productInfoParamListString);
                factoryQuoteInfo.setAttributeOption(attributeOption);
                factoryQuoteInfo.setQuoteSelfDefineParam(quoteSelfDefineParam);
                factoryQuoteInfo.setProductInfoParamList(productInfoParamList);
                factoryQuoteInfo.setCutModel(JsonUtils.map2String(cutmodelMap));
                factoryQuoteInfo.setGoodsId(goodsId);
                factoryQuoteInfo.setShowAddon(addonBuilder.toString());
                return factoryQuoteInfo;
            }
        }else {
            throw new RRException(resultMap.get("message").toString());
        }
        return null;
    }

    //将addon属性解析成集合
    private List<ProductInfoParam> addon2ProductInfoParamList(String addon){
        List<ProductInfoParam> productInfoParamList=JsonUtils.string2Collection(addon,List.class,ProductInfoParam.class);
        for (int i = 0; i <productInfoParamList.size() ; i++) {
            ProductInfoParam productInfoParam=productInfoParamList.get(i);
           StringBuilder basicStrSb=new StringBuilder();
            for (Object value : productInfoParam.getBasicParam().values()) {
                basicStrSb.append(value).append(" ");
            }
            productInfoParam.setBasicParamStr(basicStrSb.toString());
            //处理数据
            String craft=JsonUtils.map2String(productInfoParam.getCraftParam());
            craft=craft.replaceAll("\"", "").replace("{","").replace("}","");
            productInfoParam.setCraftParamStr(craft);
        }
        return productInfoParamList;
    }

    /**
     * 获取快印的算价信息
     * @param orderNo
     * @return
     */
    /**
     * 快印算价
     */
    @RequestMapping("/fastCaculateQuote")
    public R fastCaculateQuote(@RequestBody HashMap<String,Object> params){
        if(!StringUtils.isNotBlank(params.get("categoryType").toString())){
            return R.error("参数错误，请联系管理员");
        }
        //根据当前用户查询出工厂id
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        params.put("factoryId",sellerId);
        if(params.get("memberId")!=null){
            //如果是紫云分配这个客户，factoryId设置为20，写死
            if(params.get("memberId").toString().equals("898855")){
                params.put("factoryId",20);
            }
        }
        //移除memberid,请求接口
        params.remove("memberId");
        //定义一个map记录处理前的parmas
        HashMap<String,Object> paramsCopy= MapCloneUtils.clone(params);
        QuoteDto quoteDto=dealCaculateQuote(params);
        quoteDto.setErpSellerFlag(true);
        //调用算价服务
        String quoteStr=JsonUtils.object2String(quoteDto);
        logger.info("快印印刷商品算价请求数据:"+quoteStr);
        GoodsResult<QuoteResult> factoryQuote = goodsService.findFactoryQuote(quoteDto);
        String req=JsonUtils.object2String(factoryQuote);
        logger.info("快印印刷商品算价请求数据:"+req);
        //处理返回的结果
        FactoryQuoteInfo factoryQuoteInfo= dealQuoteData(req);
        if(factoryQuoteInfo==null){
            return R.error("未找到合适的算价信息!");
        }
        List<FactoryQuoteInfo> fastFactoryQuoteInfoList=new ArrayList<FactoryQuoteInfo>();
        fastFactoryQuoteInfoList.add(factoryQuoteInfo);
        return R.ok().put("fastFactoryQuoteInfoList",fastFactoryQuoteInfoList);
    }

    @RequestMapping("/isErp/{orderNo}")
     public R  isErp(@PathVariable  String orderNo ){
        Boolean flag = erpOrderService.isErpOrder(orderNo);
        return R.ok().put("flag",flag);
    }

    //获取待修改订单的信息
    @RequestMapping("updateInfo/{orderNo}")
    public R updateInfo(@PathVariable  String orderNo ){
        if(!StringUtils.isNotBlank(orderNo)){
            return R.error("获取订单信息失败");
        }
        //先查询订单信息
        ErpOrderEntity erpOrder=erpOrderService.getById(orderNo);
        //查询商品分配列表
        // 已分配列表
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("del", DeleteEnum.NOT_DELETE.toInt());
        List<ErpOrderProductionListVo> erpOrderProductionList = erpOrderProductionService.queryProductionList(params);


        //查询订单详情（erp_order_item）
        // 商品列表
        List<ErpOrderItemEntity> orderItemDetailData = erpOrderItemService.list(
                new QueryWrapper<ErpOrderItemEntity>()
                        .eq("order_no",orderNo)
                        .eq("item_del",0)
        );
        //印刷商品需将规格属性进行处理
        for (int i = 0; i <orderItemDetailData.size() ; i++) {
            ErpOrderItemEntity erpOrderItemEntity=orderItemDetailData.get(i);
            if(erpOrderItemEntity.getAddon()!=null&& erpOrderItemEntity.getAddon().contains("[{")){
                List<ProductInfoParam> productInfoParamList= addon2ProductInfoParamList(erpOrderItemEntity.getAddon());
                //拼接成addon;
                StringBuilder addonBuilder=new StringBuilder();
                for (int j=0;j<productInfoParamList.size();j++){
                    ProductInfoParam productInfoParam = productInfoParamList.get(j);
                    addonBuilder.append(productInfoParam.getPartsName()).append(":").append(productInfoParam.getBasicParamStr()).append(";");
                }
                erpOrderItemEntity.setAddon(addonBuilder.toString());
                erpOrderItemEntity.setProductInfoParamList(productInfoParamList);
            }
        }
        //商务印刷商品分类
        List<StoreGoodsCategoryEntity> shangWuCategoryData=storeGoodsCategoryService.getPrintCategoryList();
        //快印商品分类
        List<StoreGoodsCategoryEntity> fastCategoryData=storeGoodsCategoryService.getFastCateoryList();
        //查询所有门店标品商品分类
        List<StoreGoodsCategoryEntity>  categoryData=storeGoodsCategoryService.getStoreGoodsCategoryList();
        return  R.ok().put("orderItemDetailData",orderItemDetailData)
                .put("erpOrder",erpOrder)
                .put("shangWuCategoryData",shangWuCategoryData)
                .put("fastCategoryData",fastCategoryData)
                .put("categoryData",categoryData);

    }

    /**
     * 门店商品分类
     */
    @RequestMapping("/treeData")
    public R treeData(){
        List<StoreGoodsCategoryEntity>  treeData = storeGoodsCategoryService.getStoreGoodsCategoryList();
        return R.ok().put("treeData",treeData);
    }

    //获取日志
    @RequestMapping("erpOrderLog/{orderNo}")
    public R getErpOrderLog(@PathVariable String orderNo){
        if(!StringUtils.isNotBlank(orderNo)){
            return  R.error("获取日志信息失败！");
        }
        return erpOrderService.getErpOrderLog(orderNo);
    }

    /**
     * 查询工厂信息（标品商品分配）
     * @param
     * @param
     * @return
     */
    @RequestMapping("/orderItemAllotFindFactory/{eoItemId}")
    public R orderItemAllotFindFactory(@PathVariable Integer eoItemId){
        //先判断是否有绑定sku，无则提示不让分配
        ErpOrderItemEntity erpOrderItemEntity = erpOrderItemService.getById(eoItemId);
        Integer productId=erpOrderItemEntity.getProductId();
        StoreGoodsProductEntity storeGoodsProductEntity = storeGoodsProductService.getOne(new QueryWrapper<StoreGoodsProductEntity>().eq("product_id", productId).eq("disabled", 0));
        if(storeGoodsProductEntity==null){
            return  R.error("分配的商品不存在，请联系管理员!");
        }
        if(storeGoodsProductEntity.getOrigProductId()==null){
            return R.error("自营商品无法进行分配!");
        }
        //把orderItem数据插入数据到OrderInfo以及order_item中
        boolean flag=erpOrderService.copyToOrderInfo(eoItemId);
        if(!flag){
            return R.error("操作失败，请刷新页面重试！");
        }else {
            return erpOrderService.orderItemAllotFindFactory(eoItemId);
        }
    }


    /**
     * 查询工厂信息（报价商品分配）
     * @param
     * @return
     */
    @RequestMapping("/quoteOrderItemAllotFindFactory/{eoItemId}")
    public R quoteOrderItemAllotFindFactory(@PathVariable Integer eoItemId){
        //把orderItem数据插入数据到OrderInfo以及order_item中
        boolean flag=  erpOrderService.copyQuoteToOrderInfo(eoItemId);
        if(!flag){
            return R.error("操作失败，请刷新页面重试！");
        }else{
            return erpOrderService.quoteOrderItemAllotFindFactory(eoItemId);
        }
    }



    /**
     * 商品工序列表
     * @param erpItemId
     * @return
     */
    @RequestMapping("/orderCraftsInfo/{erpItemId}")
    public R orderCraftsInfo(@PathVariable("erpItemId") Integer erpItemId){
        //先保存数据到order_info以及order_item中
        //先查询是标品还是报价商品
        ErpOrderItemEntity erpOrderItemEntity=erpOrderItemService.getById(erpItemId);
        boolean flag=true;
        if(erpOrderItemEntity.getAddcartBuyType().equals("fast")||erpOrderItemEntity.getAddcartBuyType().equals("print")){
            flag=erpOrderService.copyQuoteToOrderInfo(erpItemId);
        }else{
            flag=erpOrderService.copyToOrderInfo(erpItemId);
        }
        if(flag){
            return erpOrderService.orderCraftsInfo(erpItemId);
        }else{
            return  R.error("操作失败，请刷新页面重试!");
        }

    }


    /**
     * 查询工厂信息（工艺分配）
     * @param orderCraftQuoteDto
     * @return
     */
    @RequestMapping("/orderCraftAllotFindFactory")
    public R orderCraftAllotFindFactory(@RequestBody OrderCraftQuoteDto orderCraftQuoteDto){
        return erpOrderService.orderCraftAllotFindFactory(orderCraftQuoteDto);
    }

    /**
     * 订单工艺分配
     * @return
     */
    @RequestMapping("/allotOrderCrafts")
    public R allotOrderCrafts(@RequestBody OrderCraftsDto orderCraftsDto){
        return erpOrderService.allotOrderCrafts(orderCraftsDto);
    }

    /**
     * 删除分配信息
     * @param productionId
     * @return
     */
    @RequestMapping("/deleteAllotItem")
    public R deleteAllotItem(@RequestParam("productionId") Integer productionId){
        return erpOrderService.deleteAllotItem(productionId);
    }

    /**
     * 添加外协商
     * @param orderSupplierDto
     * @return
     */
    @RequestMapping("/suppSave")
    public R suppSave(@RequestBody OrderSupplierDto orderSupplierDto){
           Integer erpItemId = orderSupplierDto.getEoItemId();
        //先保存数据到order_info以及order_item中
        //先查询是标品还是报价商品
        ErpOrderItemEntity erpOrderItemEntity=erpOrderItemService.getById(erpItemId);
        //先根据订单查询是否为紫云网订单，紫云网订单
        boolean flag=true;
        if(erpOrderItemEntity.getAddcartBuyType().equals("fast")||erpOrderItemEntity.getAddcartBuyType().equals("print")){
            flag=erpOrderService.copyQuoteToOrderInfo(erpItemId);
        }else{
            flag=erpOrderService.copyToOrderInfo(erpItemId);
        }
        if(flag){
            Long userId = UserUtils.getCurentUser().getUserId();
            return erpOrderService.suppSave(orderSupplierDto, userId);
        }else{
            return  R.error("操作失败，请刷新页面重试!");
        }
    }


    /**
     * 订单调价
     */
    @RequestMapping("/updateDiscount")
    public R updateDiscount(@RequestBody ErpOrderEntity erpOrder){
        if(!StringUtils.isNotBlank(erpOrder.getOrderNo())){
            return R.error("获取订单信息失败，请刷新页面重试");
        }
        return   erpOrderService.updateDiscount(erpOrder);
    }

    /**
     * 订单删除商品
     *
     */
    @RequestMapping("/deleteGoods/{eoItemId}")
    public R deleteGoods(@PathVariable  Integer eoItemId){
        return  erpOrderService.deleteGoods(eoItemId);
    }

    /**
     * 订单修改添加标品
     *
     */
    @RequestMapping("/addStandardGoods")
    public R addGoods(@RequestBody ErpOrderItemDto erpOrderItemDto ){
        return  erpOrderService.addStandardGoods(erpOrderItemDto);
    }

    /**
     * 订单修改添加快印
     *
     */
    @RequestMapping("/addFastGoods")
    public R addFastGoods(@RequestBody ErpOrderItemDto erpOrderItemDto ){
        return  erpOrderService.addFastGoods(erpOrderItemDto);
    }

    /**
     * 订单修改添加商务印刷
     *
     */
    @RequestMapping("/addPrintGoods")
    public R addPrintGoods(@RequestBody ErpOrderItemDto erpOrderItemDto ){
        return  erpOrderService.addPrintGoods(erpOrderItemDto);
    }

    /**
     * 修改商品价格
     */
    @RequestMapping("/startUpdatePrice")
    @RequiresPermissions("order:erporder:updatePrice")
    public R startUpdatePrice(@RequestBody ErpOrderItemDto erpOrderItemDto){
        return erpOrderService.startUpdatePrice(erpOrderItemDto);
    }

    @RequestMapping("/updatePmtGoods")
    @RequiresPermissions("order:erporder:updatePrice")
    public R updatePmtGoods(@RequestBody ErpOrderEntity erpOrder){
        return erpOrderService.updatePmtGoodsAndProjectName(erpOrder);
    }

    /**
     * 确认成本录入完成
     * @param
     * @return
     */
    @RequestMapping("/confirmCost/{orderNo}")
    public R confirmCost(@PathVariable("orderNo") String orderNo){
        return erpOrderService.confirmCost(orderNo);
    }

    /**
     * 外协订单列表
     */
    @RequestMapping("/queryOrderSupplierList")
    public R queryOrderSupplierList(@RequestBody Map<String, Object> params){
        Long sellerId = UserUtils.getCurentUser().getSellerId();
        params.put("sellerId", sellerId);
        return erpOrderProductionService.queryOrderSupplierPage(params);
    }

    /**
     * 外协批量付款
     */
    @RequestMapping("/twbOrderSuppPayment")
    public R twbOrderSuppPayment(@RequestBody TwbOrderSuppPaymentDto twbOrderSuppPaymentDto){
        return erpOrderProductionService.twbOrderSuppPayment(twbOrderSuppPaymentDto);
    }

    /**
     * 外协单批量收货
     */
    @RequestMapping("/twbOrderSuppReceiveGoods")
    public R twbOrderSuppReceiveGoods(@RequestBody Integer[] productionIds){
        return erpOrderProductionService.twbOrderSuppReceiveGoods(productionIds);
    }


    /**
     * 门店生成批量结算单
     */
    @RequestMapping("/generateBatchProduct")
    public R generateBatchProduct(@RequestBody List<String> orderList){
        return erpOrderService.generateBatchProduct(orderList);
    }


}
